/*
 * @Author: blak-kong
 * @Date: 2019-12-02 14:39:35
 * @Email: 546598185@qq.com
 */

 // model
 const Nav = require('../models/Nav');
 const { SuccessModel, ErrorModel } = require("../models/resModel")

 module.exports = {
    // 添加页面数据
    async add (ctx, next) {
        // save() 需要先给model赋值实例化
        let nav = new Nav(ctx.request.body)
        let res = await nav.save()
        ctx.body = new SuccessModel(res)
    },

    // 删除
    async delete(ctx, next) {
        console.log(ctx.params)
        let res = await Nav.deleteOne({_id: ctx.params.id})
        if (res.n && res.ok) {
            ctx.body = new SuccessModel({}, "删除成功！")
            return
        }
        ctx.body = new ErrorModel({}, "删除失败！请稍后重试！")
        return
    },

    // 更新页面数据
    async update(ctx, next) {
        let res = await Nav.updateOne({_id: ctx.params.id}, ctx.request.body)
        
    },

    // 根据 name 查询页面数据
    async query(ctx, next) {
        let res = await Nav.findOne(ctx.params)
        ctx.body = new SuccessModel(res)
    },

    async query_page (ctx, next) {
        let {size = 10, page = 1} = ctx.query;

        try {
            let options = {
                skip: Number((page-1)*size),
                limit: Number(size),
                sort:{"create_time":"-1"}
            }
            let res = await Nav.find({},null,options);     // 获取数据列表
            let total = await Nav.count();                 // 获取文档总数: mongodb文档count()已弃用  但mongoos有兼容
            ctx.body = new SuccessModel({
                list: res,
                pagination: {
                    total,
                    page : Number(page),
                    size : Number(size)
                }
            }, '获取页面数据成功')
            return
        } catch(e) {
            console.log(e);
            ctx.body = new SuccessModel({}, "获取失败，服务器异常，请稍后再试！")
            return
        }
    },
}